package com.hjt.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjt.common.constant.ProductConstant;
import com.hjt.common.to.product.SpuInfoTo;
import com.hjt.common.to.ware.SkuHasStockTo;
import com.hjt.common.to.ware.SkuReductionTo;
import com.hjt.common.to.ware.SpuBoundTo;
import com.hjt.common.to.es.SkuEsModel;
import com.hjt.common.utils.PageUtils;
import com.hjt.common.utils.Query;
import com.hjt.common.utils.R;
import com.hjt.gulimall.product.dao.SpuInfoDao;
import com.hjt.gulimall.product.entity.*;
import com.hjt.gulimall.product.feign.CouponFeignService;
import com.hjt.gulimall.product.feign.SearchFeignService;
import com.hjt.gulimall.product.feign.WareFeignService;
import com.hjt.gulimall.product.service.*;
import com.hjt.gulimall.product.vo.sku.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService attrValueService;
    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存商品发布信息
     *
     * @param spuSaveVo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 1.保存spu基本信息 // pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        Long spuId = spuInfoEntity.getId();

        // 2.保存Spu描述图片  pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(spuInfoDescEntity);


        // 3.保存图片集 // pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuId,images);

        // 4.保存规格参数 // pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(baseAttr -> {
            ProductAttrValueEntity attrEntity = new ProductAttrValueEntity();
            attrEntity.setSpuId(spuId);
            AttrEntity attr = attrService.getById(baseAttr.getAttrId());
            BeanUtils.copyProperties(attr, attrEntity);
            attrEntity.setAttrValue(baseAttr.getAttrValues());
            attrEntity.setQuickShow(baseAttr.getShowDesc());
            return attrEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttrList(productAttrValueEntities);

        // 5.保存spu的积分信息 sms_spu_bounds（积分表）
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        R response = couponFeignService.saveSpuBounds(spuBoundTo);
        if (response.getCode() != 0) {
            log.error("远程调用saveSpuBounds方法失败");
        }

        // 5.保存当前spu下的所有sku信息
        List<Skus> skuList = spuSaveVo.getSkus();
        if (!CollectionUtils.isEmpty(skuList))  {
            skuList.forEach(sku -> {
                // 5.1 sku的基本信息 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                // 默认图片
                String defaultImage = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImage = image.getImgUrl();
                    }
                }
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.save(skuInfoEntity);

                // 5.2 sku的图片信息 pms_sku_images
                // TODO:没有图片；路径无需保存
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImageEntityList = sku.getImages().stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    return skuImagesEntity;
                }).filter(skuImagesEntity -> StringUtils.hasLength(skuImagesEntity.getImgUrl())).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImageEntityList);

                // 5.3 sku的销售属性信息  pms_sku_sale_attr_value
                List<Attr> saleAttrList = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = saleAttrList.stream().map(saleAttr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(saleAttr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);

                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);
                /*
                 *  5.4 sku的优惠，满减信息 gulimall_sms -->
                 *  sms_member_price(会员价格表)
                 *  sms_sku_ladder（商品阶梯价格）
                 *  sms_sku_full_reduction（满减表 ）
                 */
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                skuReductionTo.setSkuId(skuId);
                BeanUtils.copyProperties(sku, skuReductionTo);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0))>0){
                    final R resp = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (resp.getCode() != 0) {
                        log.error("远程调用saveSpuBounds方法失败");
                    }
                }

            });
        }

    }

    /**
     * 条件查询分页
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        //  拼装查询条件
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            // 模糊查询spu名称或id
            wrapper.and(obj -> {
                obj.like("spu_name",key).or().eq("id", key);
            });
        }
        // 状态查询
        String status = (String) params.get("status");
        if (StringUtils.hasLength(status)) {
            wrapper.eq("publish_status",status);
        }
        // 品牌id
        String brandId = (String) params.get("brandId");
        if (StringUtils.hasLength(brandId)) {
            try {
                if (Integer.parseInt(brandId) > 0) {
                    wrapper.eq("brand_id",brandId);
                }
            }
            catch (NumberFormatException exception) {
                log.warn("品牌id小于等于0,====>"+brandId);
            }
        }
        // 三级分类id
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.hasLength(catelogId)) {
            try {
                if (Integer.parseInt(catelogId) > 0) {
                    wrapper.eq("catalog_id",catelogId);
                }
            }
            catch (NumberFormatException exception) {
                log.warn("分类id小于等于0,====>"+catelogId);
            }
        }
        // 排序
        String order = (String) params.get("order");
        if (StringUtils.hasLength(order)) {
            if (order.equalsIgnoreCase("asc")) {
                wrapper.orderByAsc();
            } else {
                wrapper.orderByDesc();
            }
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
//        page.getRecords().stream().map(spuInfoEntity -> {
//            SpuResponseVo spuResponseVo = new SpuResponseVo();
//            BeanUtils.copyProperties(spuInfoEntity,spuResponseVo);
//            return spuResponseVo;
//        });
        return new PageUtils(page);
    }


    /**
     * 商品上架，上架一个SPU
     * 1.查询出该spu下的所有sku信息（）
     * 2.查询出该spu下的所有【可检索】的属性
     * 3.查询出每个sku的库存信息（调用仓储服务接口）
     * 4.封装成可以检索的skuEsModel
     * 4.保存 skuEsModel 到ElasticSearch中（调用search服务接口）
     *
     * @param spuId
     */
    @Override
    @Transactional
    public void up(Long spuId) {

        // 1.查出当前spuId下对应的所有sku信息
        List<SkuInfoEntity> skuInfoEntityList =  skuInfoService.listBySpuId(spuId);

        // 2.查出spu的所有可检索属性
        // 2.1 查出spu的所有属性
        List<ProductAttrValueEntity> attrValueEntityList = attrValueService.listBySpuId(spuId);
        // 2.2 查出所有可被检索的属性id
        List<Long> attrIdList = attrValueEntityList.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> searchableAttrIds = attrService.selectSearchableAttrIds(attrIdList);
        // 2.3 过滤出所有可以被检索的属性值,并封装成SkuEsModel的静态内部类
        List<SkuEsModel.Attr> attrs = attrValueEntityList.stream()
                .filter(attrValueEntity -> searchableAttrIds.contains(attrValueEntity.getAttrId()))
                .map(attrValueEntity -> {
                    SkuEsModel.Attr attr = new SkuEsModel.Attr();
                    BeanUtils.copyProperties(attrValueEntity, attr);
                    return attr;
                })
                .collect(Collectors.toList());
        // 3.查询仓储信息
        Map<Long, Boolean> skuHasStockToMap = null;
        try{
            List<Long> skuIdList = skuInfoEntityList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            // 3.1远程调用仓储服务的接口。获取每个sku是否有库存的信息（{skuId,hasStock}）
            R skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
            // R是一个Map，存储到其中的信息会被转换成map，所以在getData中做了处理
            TypeReference<List<SkuHasStockTo>> typeReference = new TypeReference<List<SkuHasStockTo>>(){};
            List<SkuHasStockTo> skuHasStockToList = skuHasStock.getData(typeReference);
            skuHasStockToMap = skuHasStockToList.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
        } catch (Exception e) {
            log.error("查询仓储库存出错:{0}",e);
        }

        // 4.封装每个sku信息
        Map<Long, Boolean> finalSkuHasStockToMap = skuHasStockToMap;
        List<SkuEsModel> skuEsModelList = skuInfoEntityList.stream().map(skuInfoEntity -> {
            // skuEntity中有的基本数据
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());

            // 库存信息
            if (finalSkuHasStockToMap != null) {
                // 设置每个sku是否有库存
                skuEsModel.setHasStock(finalSkuHasStockToMap.get(skuEsModel.getSkuId()));
            }
            // 热度评分
            skuEsModel.setHotScore(0L);
            // 品牌信息
            BrandEntity brandEntity = brandService.getById(skuInfoEntity.getBrandId());
            if (brandEntity != null) {
                skuEsModel.setBrandName(brandEntity.getName());
                skuEsModel.setBrandImg(brandEntity.getLogo());
            }
            // 分类信息
            CategoryEntity categoryEntity = categoryService.getById(skuInfoEntity.getCatalogId());
            if (categoryEntity != null) {
                skuEsModel.setCatalogName(categoryEntity.getName());
            }
            // 设置可以被检索的规格属性
            skuEsModel.setAttrs(attrs);
            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO: 5.存储到ElasticSearch中
        R r = searchFeignService.productStatusUp(skuEsModelList);
        if (r.getCode().equals(0)) {
            // 上架成功，更新spu的状态
            this.updateSpuStatus(spuId, ProductConstant.StatusEnum.UP_STATUS.getCode());
        } else {
            // TODO:上架失败，重试
        }
    }


    // 更新商品状态
    @Override
    public void updateSpuStatus(Long spuId, int code) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setPublishStatus(code);
        baseMapper.update(spuInfoEntity, new QueryWrapper<SpuInfoEntity>().eq("id", spuId));
    }

    @Override
    public SpuInfoTo getBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        if (skuInfoEntity == null) {
            log.error("未查到sku信息:skuId="+skuId);
            return null;
        }
        Long spuId = skuInfoEntity.getSpuId();
        SpuInfoEntity spuInfoEntity = baseMapper.selectById(spuId); // spu信息
        BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId()); // 品牌信息（品牌名称）
        SpuInfoTo spuInfoTo = new SpuInfoTo();
        BeanUtils.copyProperties(spuInfoEntity, spuInfoTo);
        spuInfoTo.setBrandName(brandEntity.getName());
        return spuInfoTo;
    }
}